import queue
from threading import Thread
from time import sleep
 
# 生产者函数
def producer(q, items):
    for item in items:
        print(f"Producing {item}.")
        sleep(0.5)  # 模拟工作延迟
        q.put(item)
 
# 消费者函数
def consumer(q):
    while True:
        item = q.get()
        if item is None:  # 消费者通过放置None来表示结束
            break
        print(f"Consuming {item}.")
        sleep(0.5)  # 模拟工作延迟
        q.task_done()  # 通知任务完成
 
# 主程序
def main():
    q = queue.Queue()
    items = ['item{}'.format(i) for i in range(5)]
 
    # 启动生产者线程
    producer_thread = Thread(target=producer, args=(q, items))
    producer_thread.start()
 
    # 启动消费者线程
    consumer_thread = Thread(target=consumer, args=(q,))
    consumer_thread.daemon = True  # 确保消费者线程随主线程结束
    consumer_thread.start()
 
    # 等待生产者完成
    producer_thread.join()
 
    # 通知消费者结束
    for i in range(len(items)):
        q.put(None)
 
    # 等待所有已经加入队列的task都被处理完
    q.join()
 
if __name__ == '__main__':
    main()